import Vue from 'vue'
// div拖拽功能
const drag = Vue.directive('drag', {
    bind (el, binding) {
        el.onmousedown = e => {
            let x = e.pageX - el.offsetLeft
            let y = e.pageY - el.offsetTop
            let maxLeft, maxTop
            if (binding.value) {
                let { wrap, current } = binding.value
                let node1 = document.getElementById(wrap)
                let node2 = document.getElementById(current)
                maxLeft = node1.offsetWidth - node2.offsetWidth
                maxTop = node1.offsetHeight - node2.offsetHeight
            }
            document.onmousemove = e => {
                let left = e.pageX - x
                let top = e.pageY - y
                if (binding.value) {
                    if (left >= 0) {
                        left = 0
                    }
                    if (top >= 0) {
                        top = 0
                    }
                    if (left <= maxLeft) {
                        left = maxLeft
                    }
                    if (top <= maxTop) {
                        top = maxTop
                    }
                }
                el.style.left = `${left}px`
                el.style.top = `${top}px`
            }
            document.onmouseup = () => {
                document.onmousemove = document.onmousedown = null
            }
            e.preventDefault()
        }
    }
})
export default { drag }
